package com.test.fastdfs.demo.controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.test.fastdfs.demo.entity.FileModel;
import com.test.fastdfs.demo.service.FastefsClient;
import com.test.fastdfs.demo.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.*;
import java.util.List;


/**
 * @author cy
 */
@Controller
@RequestMapping("/file")
public class PicUtilController {
    @Value("${file.path.head}")
    private String pathHead;

    @Autowired
    private FastefsClient fastefsClient;

    @Autowired
    private FileService fileService;


    public static final HashMap<String, java.util.List<String>> EXT_MAP = new HashMap<>();//支持的文件类型，目前不限制
    public static final List<String> IMGE_TYPES = Arrays.asList("gif", "jpg", "jpeg", "png", "bmp");

    static {
        EXT_MAP.put("image", IMGE_TYPES);
        EXT_MAP.put("flash", Arrays.asList("swf", "flv"));
        EXT_MAP.put("media", Arrays.asList("swf", "flv", "mp4", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb"));
        EXT_MAP.put("file", Arrays.asList("doc", "docx", "xls", "xlsx", "ppt", "htm", "html", "txt", "zip", "rar", "gz", "bz2","pdf"));
    }


    /**
     * 上传图片
     *
     * @return
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public void uploadPic(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (multipartFile == null) {
                return;
            }
            String fileOriginalName =multipartFile.getOriginalFilename();
            String filename = fastefsClient.uploFile(multipartFile);
            FileModel fileModel = new FileModel();
            fileModel.setPathInfo(pathHead + filename);
            fileModel.setOriginalName(fileOriginalName);
            String[] splitName = filename.split("\\.");
            String extFileName = splitName[1];
            fileModel.setExt(extFileName);
            boolean flag = false;

            for (String imageExtname : IMGE_TYPES) {
                if (imageExtname.equals(extFileName)) {
                    fileModel.setType("image");
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                for (String extName : EXT_MAP.get("media")) {
                    if (extName.equals(extFileName)) {
                        fileModel.setType("media");
                        flag = true;
                        break;
                    }
                }

            }
            if (!flag) {
                for (String extName : EXT_MAP.get("file")) {
                    if (extName.equals(extFileName)) {
                        fileModel.setType("file");
                        flag = true;
                        break;
                    }
                }
            }

            fileModel.setCreateTime(new Date());
            fileService.createFile(fileModel);

            ObjectMapper mapper = new ObjectMapper();
            String ret = mapper.writeValueAsString(fileModel);
            response.setContentType("application/json;charset=utf8");
            response.getOutputStream().write(ret.getBytes());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @RequestMapping(value = "/deleteFile")
    @ResponseBody
    public Map deletePic(HttpServletRequest request) {
        HashMap<String,Object> result =new HashMap();
        result.put("code",-1);
        result.put("msg","删除失败");
        try {
            String fullfile = request.getParameter("filename");
            Long id = Long.parseLong(request.getParameter("id"));
            if (!StringUtils.isEmpty(fullfile)) {
                String filename = fullfile.replace(pathHead, "");
                fastefsClient.deleteFile(filename);
                FileModel fileModel = new FileModel();
                fileModel.setId(id);
                fileService.deleteFile(fileModel);
                result.put("code",0);
                result.put("msg","删除成功");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }


    @RequestMapping(value = "/listFile")
    @ResponseBody
    public Map addFile(HttpServletRequest request) {
        HashMap<String,Object> result =new HashMap();
        result.put("code",0);
        result.put("msg","查询成功");
        String fileName = request.getParameter("file");
        FileModel fileModel = new FileModel();
        fileModel.setPathInfo(fileName);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withMatcher("pathInfo", ExampleMatcher.GenericPropertyMatchers.contains()) //姓名采用“开始匹配”的方式查询
                .withIgnorePaths("focus");  //忽略属性：是否关注。因为是基本类型，需要忽略掉
        Example example = Example.of(fileModel,matcher);
        List<FileModel> fileModels = fileService.findAllByCondition(example);
        result.put("data",fileModels);
        return result;
    }
}
